package com.amkai.aes.webservice.binary.objecthandler.registration;

import java.io.Serializable;

import com.amkai.aes.aescommon.service.binary.job.ExternalIdJob;
import com.amkai.aes.aescommon.service.binary.job.registration.ExternalIdJobResult;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class ExternalIdJobHandler implements JobObjectHandler<ExternalIdJob, Serializable, ExternalIdJobResult> {

	@Override
	public ExternalIdJobResult process(ExternalIdJob job, Serializable object) throws Exception {
		ExternalIdJobResult result = new ExternalIdJobResult();
		if (job.getExternalId()!=null) {
			SessionManager sm = SiteManager.Start();
			String qstr ="select count(x.id) from ExternalId as x where";
			if (job.getExternalId().getExternalId()==null || job.getExternalId().getExternalId().isEmpty())
				qstr += " x.externalId is null";
			else
				qstr += " x.externalId = '" + job.getExternalId().getExternalId() + "'";
			if (job.getExternalId().getType()==null)
				qstr += " and x.type is null";
			else
				qstr += " and x.type.id = " + job.getExternalId().getType().getId();
			if (job.getExternalId().getId()!=null)
				qstr += " and x.id <> " + job.getExternalId().getId();
			Number nbr = (Number)sm.execute(qstr).uniqueResult();
			result.setUnique(nbr==null || nbr.intValue()==0);
		}
		return result;
	}

}
